<!--物流进度-->
<style lang="less" scoped>
  .NodeName {
    color: #999;
  }
  .pro-map-wrap {
    background: #fff;
  }
  .ExcuteState {
    font-size: 14px;
    line-height: 32px;
    color: #666;
  }
  .ExcuteDate {
    color: #888;
    line-height: 12px;
  }
  .prog-step-wrap {
    padding: 20px 0 0.2rem 15px;
  }
  .prog-step {
    padding-left: 15px;
  }
  .prog-step-dl:after {
    width: 14px;
    height: 14px;
    left: -24px;
    top: 13px;
  }
  .PoDate {
    color: #999;
  }
  .prog-wrap {
    padding: 0;
    div {
      &:first-of-type {
        padding-top: 5px;
      }
      &:last-of-type {
        padding-bottom: 5px;
      }
    }
    p,
    label {
      font-size: 14px;
      padding: 0 0.2rem;
    }
    .BillNo {
      font-size: 16px;
      padding:10px 0.2rem;
    }
    .displayflex {
      label {
        color: #888;
      }
      p {
        color: #888;
        &:last-child {
          text-align: right;
        }
      }
    }
  }
.mb30{
  margin:0 0 15px;
}
</style>

<template>
  <div class="contain">
    <app-header></app-header>
    <div class="prog-wrap" v-bind:class="tabNo === 1?'mb30':''">
      <p
        class="BillNo"
        v-bind:style="tabNo === 1?'border-bottom: 1px solid #ccc;':''"
      >业务单号：{{data.BbMain.BBillNo}}</p>
      <div v-if="tabNo === 1">
        <!-- <div class="displayflex">
          <label>采购单号</label>
          <p class="flex1">{{data.BbMain.PoBillNo}}</p>
        </div>-->
        <div class="displayflex">
          <label>客户名称</label>
          <p class="flex1">{{data.BbMain.SaleCorpName}}</p>
        </div>
        <div class="displayflex">
          <label>地址</label>
          <!-- <p class="flex1" v-if="data.PoMain.ArrivalAddress && data.PoMain.ArrivalAddress !== ''">{{data.PoMain.ArrivalAddress}}</p> -->
          <p
            class="flex1"
          >{{data.PoMain.ArrivalProvince | province}}{{data.PoMain.ArrivalCity | city}}{{data.PoMain.ArrivalDistrict | district}}{{data.PoMain.ArrivalAddress}}</p>
        </div>
        <div class="displayflex">
          <p class="flex1">品种数</p>
          <p class="flex1">
            <em class="org">{{data.BbMain.CountSum}}</em> 个
          </p>
        </div>
        <div class="displayflex">
          <p class="flex1">总数量</p>
          <p class="flex1">
            <em class="org">{{data.BbMain.Pkgs}}</em> 件
          </p>
        </div>
      </div>
    </div>
    <div class="lltab ft14">
      <tab bar-active-color="#77babd" defaultColor="#333333" active-color="#77babd" :line-width="2">
        <tab-item selected @on-item-click="tabNo = 1">进度跟踪</tab-item>
        <tab-item @on-item-click="tabNo = 2" v-bind:disabled="data.PoMain === null">配送详情</tab-item>
      </tab>
    </div>
    <div class="prog-step-wrap" v-show="tabNo === 1">
    <template v-if="showProgress">
      <div class="prog-step" v-if="semiTraceData.length>0">
        <dl class="prog-step-dl" v-for="item in semiTraceData">
          <dd class="ExcuteState">{{item.content}}</dd>
          <dt class="ExcuteState">{{item.title}}</dt>
          <dd class="ExcuteDate">{{item.time}}</dd>
        </dl>
        <!-- <dl class="prog-step-dl" v-for="item in progressNode">
            <dd class="NodeName">类型：{{item.NodeName || '物流状态'}}</dd>
            <dt class="ExcuteState" v-if="item.ExcuteState.indexOf('P') > -1">{{item.ExcuteState | billstate}}</dt>
            <dt class="ExcuteState" v-else>{{item.ExcuteState | PoState}}</dt>
            <dd class="ExcuteDate">{{item.ExcuteDate | time}}</dd>
        </dl>-->
      </div>
      <div v-else class="no-data-check progress">
        <i class="llse llse-qianshou"></i>
        <p>平台没有进度信息</p>
      </div>
    </template>
    </div>
    <div v-show="tabNo === 2">
      <div id="allmap" style="height:65vh;"></div>
      <div class="pro-map-wrap" v-if="PoMain.ArrivalCity">
        <div class="displayflex pro-map-head">
          <dl class="flex1">
            <dt>到达:{{PoMain.ArrivalCity | city}}</dt>
            <dd>{{PoMain.ArrivalDistrict | district}} {{PoMain.ArrivalAddress}}</dd>
            <dd class="PoDate">{{PoMain.ArrivalArrivedDate | time}}</dd>
          </dl>
          <dl>
            <dt>起点:{{PoMain.DepartureCity | city}}</dt>
            <dd>{{PoMain.DepartureDistrict | district}} {{PoMain.DepartureAddress}}</dd>
            <dd class="PoDate">{{PoMain.DepartureDate | time}}</dd>
          </dl>
        </div>
        <div class="pro-map-body">
          <div class="pm-logis displayflex">
            <span class="tag">物</span>
            <div class="flex1">
              <p>{{Vehicle.DeliverName || '暂无信息'}}</p>
              <em>{{PoMain.TPLPoNo}}</em>
            </div>
          </div>
          <div class="pm-driver displayflex">
            <i class="iconfont icon-driver"></i>
            <template v-if="Object.keys(Vehicle).length === 0">
              <span>暂无信息</span>
            </template>
            <template v-else>
              <span>{{Vehicle.Driver1Name}}</span>
              <em class="flex1">{{Vehicle.PlateNumber}}</em>
              <span>
                {{Vehicle.Driver1Tel || Vehicle.Driver2Tel || kfNumber}}
                <a
                  :href="'tel://'+ (Vehicle.Driver1Tel || Vehicle.Driver2Tel || kfNumber)"
                  class="iconfont icon-phone org"
                ></a>
              </span>
            </template>
          </div>
        </div>
      </div>
      <div v-else class="no-data-check"><i class="llse llse-qianshou"></i><p>无起始地或目的地信息</p> 
      </div>
    </div>
  </div>
</template>

<script>
import appHeader from "@/components/core/header/app_header.vue";
export default {
  components: {
    appHeader
  },
  name: "progresss",
  data() {
    return {
      tabNo: 1,
      data: {
        PoMain: {},
        BbMain: {},
        BbDetailList: []
      },
      time: "",
      progressNode: [],
      PoMain: {},
      Vehicle: {},
      filter: this.$options.filters,
      kfNumber: "400-056-1858",

      map: null,
      points: [],
      addressStart: "",
      addressEnd: "",

      semiTraceData: [],
      driverList: [
        {
          name: "刘师傅",
          tel: "18086466002"
        },
        {
          name: "王师傅",
          tel: "18086466021"
        },
        {
          name: "柳师傅",
          tel: "18672348869"
        },
        {
          name: "李师傅",
          tel: "18086466050"
        },
        {
          name: "黄伟",
          tel: "15671212897"
        },
        {
          name: "王奕",
          tel: "13971607247"
        }
      ],
      showProgress:false
    };
  },
  watch: {
    tabNo(n, o) {
      if (n == 2 && this.PoMain && this.map == null) {
        this.$nextTick(() => {
          this.LoadMap();
        });
      }
    }
  },
  created() {
    this.getdata();
  },
  computed: {
    userinfo() {
      return localStorage.getItem("userinfo") === null
        ? null
        : JSON.parse(localStorage.getItem("userinfo"));
    },
    Guid() {
      return this.$route.query.Guid ? this.$route.query.Guid : null;
    },
    MainPoGuid() {
      return this.$route.query.MainPoGuid ? this.$route.query.MainPoGuid : null;
    },
    BBillGuid() {
      return this.$route.query.BBillGuid ? this.$route.query.BBillGuid : null;
    },
    Qty() {
      let Qty = 0;
      this.data.BbDetailList.forEach(x => {
        Qty += x.Qty;
      });
      return Qty;
    }
  },
  methods: {
    getdata() {
      var slef =this;
      var query = {
        Guid: this.Guid,
        MainPoGuid: this.MainPoGuid,
        BBillGuid: this.BBillGuid,
        TenantGuid: this.userinfo.TenantGuid,
        CorpGuid: this.userinfo.CorpGuid
      };
      this.Ajax.post("LogisticsOrderTracking", query).then(resp => {
        if (resp.IsSuccess) {
          this.data = resp.Data;
          if (this.data.PoMain) this.PoMain = this.data.PoMain;
          if (this.data.Vehicle) this.Vehicle = this.data.Vehicle;

          if (this.PoMain) {
            this.addressStart = `${this.filter.province(
              this.PoMain.DepartureProvince
            )}${this.filter.city(
              this.PoMain.DepartureCity
            )}${this.filter.district(this.PoMain.DepartureDistrict)}${
              this.PoMain.DepartureAddress
            }`;
            this.addressEnd = `${this.filter.province(
              this.PoMain.ArrivalProvince
            )}${this.filter.city(
              this.PoMain.ArrivalCity
            )}${this.filter.district(this.PoMain.ArrivalDistrict)}${
              this.PoMain.ArrivalAddress
            }`;
          }

          if (this.data.TracingList) {
            this.progressNode = this.progressNode.concat(this.data.TracingList);
            this.progressNode.forEach(item => {
              var stateinfo = `${this.filter.PoState(item.ExcuteState)}`;
              var content = stateinfo;
              if (item.ExcuteState == "41") {
                content =
                  "【" + this.data.PoMain.DeliverName + "】" + stateinfo;
              }
              if (item.ExcuteState == "44") {
                content =
                  "【" + this.data.PoMain.DeliverName + "】" + stateinfo;
              }
              if (item.ExcuteState == "51") {
                content =
                  stateinfo +
                  ", 司机：" +
                  this.data.Vehicle.Driver1Name +
                  "，电话：" +
                  this.data.Vehicle.Driver1Tel;
              }
              if (item.ExcuteState == "52") {
                content =
                  "货物已装车，提货件数：" +
                  this.data.BbMain.Pkgs +
                  "件，发往【" +
                  this.data.BbMain.SaleCorpName +
                  "】";
              }
              if (item.ExcuteState == "56") {
                content =
                  "货物已由" +
                  "【" +
                  this.data.Vehicle.Driver1Name +
                  "】交接确认，交接件数：" +
                  this.data.BbMain.Pkgs +
                  "件，请准备收货。";
              }
              if (item.ExcuteState == "81") {
                content =
                  "货物已完成配送 | 签收人：" +
                  this.data.PoMain.Receiver +
                  "，签收件数：" +
                  this.data.BbMain.Pkgs +
                  "件。";
              }
              var itemdata = {
                content: content,
                //title: stateinfo,
                time: `${this.filter.timeCX(item.CreateTime)}`
              };
              this.semiTraceData.push(itemdata);
              //console.log(item.ExcuteState);
            });
            this.showProgress = true;
          }

          if (this.data.GpsList && this.data.GpsList.length > 0) {
            this.data.GpsList.forEach(x => {
              let item = JSON.parse(x.DrivePositionGIS);
              this.points.push(new BMap.Point(item.lng, item.lat));
            });
          } else {
            var myGeo = new BMap.Geocoder();
            //console.log(this.addressStart);
            myGeo.getPoint(
              this.addressStart,
              function(point) {
                console.log(point);
                slef.points.push(new BMap.Point(point.lng,point.lat));
              },
              this.addressStart
            );
          }
        } else {
          this.Toast({
            message: resp.ErrorMessage || "列表为空，请稍后刷新"
          });
        }
      });
    },
    LoadMap() {
      let self = this,
        mapStyle = {
          styleJson: [
            {
              featureType: "water",
              elementType: "all",
              stylers: {
                color: "#62b9c0"
              }
            },
            {
              featureType: "land",
              elementType: "all",
              stylers: {
                color: "#f3f3f3"
              }
            },
            {
              featureType: "railway",
              elementType: "all",
              stylers: {
                visibility: "off"
              }
            },
            {
              featureType: "highway",
              elementType: "all",
              stylers: {
                color: "#dae9e6"
              }
            },
            {
              featureType: "highway",
              elementType: "labels",
              stylers: {
                visibility: "off"
              }
            },
            {
              featureType: "arterial",
              elementType: "geometry",
              stylers: {
                color: "#fefefe"
              }
            },
            {
              featureType: "arterial",
              elementType: "geometry.fill",
              stylers: {
                color: "#fefefe"
              }
            },
            {
              featureType: "poi",
              elementType: "all",
              stylers: {
                visibility: "on"
              }
            },
            {
              featureType: "green",
              elementType: "all",
              stylers: {
                visibility: "off"
              }
            },
            {
              featureType: "subway",
              elementType: "all",
              stylers: {
                visibility: "off"
              }
            },
            {
              featureType: "manmade",
              elementType: "all",
              stylers: {
                color: "#d1d1d1"
              }
            },
            {
              featureType: "local",
              elementType: "all",
              stylers: {
                color: "#d1d1d1"
              }
            },
            {
              featureType: "arterial",
              elementType: "labels",
              stylers: {
                visibility: "off"
              }
            },
            {
              featureType: "boundary",
              elementType: "all",
              stylers: {
                color: "#8eaeb1"
              }
            },
            {
              featureType: "building",
              elementType: "all",
              stylers: {
                color: "#d1d1d1"
              }
            },
            {
              featureType: "label",
              elementType: "labels.text.fill",
              stylers: {
                color: "#666666"
              }
            },
            {
              featureType: "district",
              elementType: "labels.text.fill",
              stylers: {
                color: "#444"
              }
            },
            {
              featureType: "district",
              elementType: "labels.text.stroke",
              stylers: {
                color: "#EFEFEF"
              }
            }
          ]
        };

      let top_right_navigation = new BMap.NavigationControl({
          anchor: BMAP_ANCHOR_TOP_RIGHT,
          type: BMAP_NAVIGATION_CONTROL_SMALL
        }), //右上角，仅包含平移和缩放按钮
        GeoCoder = new BMap.Geocoder();

      this.map = new BMap.Map("allmap");
      this.map.setMapStyle(mapStyle);
      this.map.addControl(top_right_navigation);
      this.map.enableScrollWheelZoom();

      //设定起止点
      let fc = this.$options.filters["city"],
        myGeo = new BMap.Geocoder(),
        AddressPair = [this.addressStart, this.addressEnd],
        IcoPair = ["/Static/images/start.png", "/Static/images/end.png"],
        AddressTxtPair = [
          fc(this.PoMain.DepartureCity),
          fc(this.PoMain.ArrivalCity)
        ],
        PointPair = [];

      runAsync().then(x => {
        if (x === true) {
          if (this.addressstart !== "" && this.addressend !== "") {
            this.setZoom(PointPair);
            this.setRoute(PointPair);
          }
          let polyline = drawRoute();
          this.map.addOverlay(self.car);
          this.map.addOverlay(polyline); //增加折线
        } else {
          this.Toast({
            message: "起始地址没有解析到结果，请刷新重试"
          });
        }
      });

      function drawRoute() {
        let driving = new BMap.DrivingRoute(self.map),
          polylinelist = [];

        self.points.forEach(element => {
          polylinelist.push(new BMap.Point(element.lng, element.lat));
        });
        let polyline = new BMap.Polyline(polylinelist, {
          strokeColor: "black",
          strokeWeight: 5,
          strokeOpacity: 1
        });

        self.car = new BMap.Marker(self.points[self.points.length - 1], {
          icon: new BMap.Icon("/Static/images/car.png", new BMap.Size(52, 32), {
            anchor: new BMap.Size(27, 13)
          })
        });

        return polyline;
      }

      function runAsync() {
        let promise = new Promise((resolve, reject) => {
          AddressPair.forEach((x, i) => {
            myGeo.getPoint(
              x,
              function(point) {
                if (point) {
                  PointPair.push(point);
                  let Mark = new BMap.Marker(point, {
                    icon: new BMap.Icon(IcoPair[i], new BMap.Size(36, 36), {
                      anchor: new BMap.Size(18, 36)
                    })
                  });
                  self.map.addOverlay(Mark);
                  if (PointPair.length === AddressPair.length) {
                    resolve(true);
                  }
                } else {
                  reject(false);
                }
              },
              AddressTxtPair[i]
            );
          });
        });
        return promise;
      }
    },
    // 根据点的数组自动调整缩放级别
    setZoom(bPoints) {
      let view = this.map.getViewport(eval(bPoints)),
        mapZoom = view.zoom,
        centerPoint = view.center;
      this.map.centerAndZoom(centerPoint, mapZoom);
    },
    setRoute(bPoints) {
      let driving = new BMap.DrivingRoute(this.map, {
        renderOptions: {
          map: this.map,
          autoViewport: true
        },
        onPolylinesSet: routes => {
          let searchRoute = routes[0].getPolyline(); //导航路线
          searchRoute.setStrokeColor("#62b9c0");
          searchRoute.setStrokeOpacity(1);
          this.map.addOverlay(searchRoute);
        },
        onMarkersSet: routes => {
          this.map.removeOverlay(routes[0].marker); //删除起点
          this.map.removeOverlay(routes[1].marker); //删除终点
        }
      });
      driving.search(bPoints[0], bPoints[1]);
    },

    //随机生成时间
    getRandomTime() {
      let arr = new Array(),
        d = new Date(this.PoMain.BillDate),
        Y = d.getFullYear(),
        M = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1,
        D = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate(),
        h = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours(),
        m = d.getMinutes() < 10 ? `0${d.getHours()}` : d.getHours(),
        s = d.getSeconds() < 10 ? `0${d.getHours()}` : d.getHours();
      for (var i = 0; i < this.semiTraceData.length; i++) {
        arr.push(
          `${Y}-${M}-${D} ${grn(20, parseInt(h))}:${grn(60, parseInt(m))}:${grn(
            60,
            parseInt(s)
          )}`
        );
      }
      return arr;

      function grn(min, max) {
        let s = max - min,
          n = Math.floor(Math.random() * s + min);
        return n < 0 ? `0${n}` : n;
      }
    }
  }
};
</script>